﻿using RockBus.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace RockBus.DataContracts
{
    [DataContract(Namespace = StringConstants.RockBusNamespace)]
    public class PersistenceMessage
    {
        private PersistenceMessage()
        {
        }

        public PersistenceMessage(RoutingHeader routingHeader, string messageVersion, string messageAction, ReceivePortInfo rpi, DateTime receiveTime, string receiveAddress, byte[] payload)
        {
            this.RoutingHeader = routingHeader;
            this.MessageVersion = messageVersion;
            this.MessageAction = messageAction;
            this.ReceivePortInfo = rpi;
            this.ReceiveTime = receiveTime;
            this.ReceiveAddress = receiveAddress;
            this.Payload = payload;
        }

        [DataMember]
        public RoutingHeader RoutingHeader { get; set; }

        [DataMember]
        public CorrelationHeader CorrelationHeader { get; set; }

        [DataMember]
        public TopicHeader TopicHeader { get; set; }

        [DataMember]
        public string MessageVersion { get; set; }

        [DataMember]
        public string MessageAction { get; set; }

        [DataMember]
        public ReceivePortInfo ReceivePortInfo { get; set; }

        [DataMember]
        public DateTime ReceiveTime { get; set; }

        [DataMember]
        public string ReceiveAddress { get; set; }

        [DataMember]
        public byte[] Payload { get; set; }

        public Message CreateMessage()
        {
            var ms = new MemoryStream(this.Payload);
            var xr = XmlReader.Create(ms);

            var mv = Conversions.ConvertWithTypeConverter<string, MessageVersion>(this.MessageVersion);
            return Message.CreateMessage(xr, 4096, mv);
        }
    }
}
